<?php

App::uses('AppModel', 'Model');

/**
 * User Model
 * 
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       Green.Model
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 *
 * @property Role $Role
 */
class User extends AppModel {

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'fullname';

    /**
     * Core Role map value key
     * - `administrator` - Value of user group admin full control access.
     * - `authenticated` Value of authenticated user.
     * - `anonymous` - Value of user group public.
     *
     * @var array
     */
    protected $_roleMap = array(
        'administrator' => 3,
        'authenticated' => 2,
        'anonymous' => 1
    );

    /**
     * List of behaviors
     *
     * @var array
     */
    public $actsAs = array(
        'Containable'
    );

    /**
     * Defined to load the config file stored.
     *
     * @var string
     */
    public $configKey = 'User';

    /**
     * Timestamp Unix maps.
     *
     * @var array
     */
    public $timestamp = array(
        'birthday' => 'date',
        'lastvisited' => 'datetime',
        'created' => 'datetime',
        'updated' => 'datetime'
    );

    /**
     * Validation rules.
     *
     * @var array
     */
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => '//',
                'on' => 'create',
                'required' => true,
                'message' => 'This field is not blank!',
            ),
            'notempty' => array(
                'allowEmpty' => false,
                'rule' => 'notempty',
                'message' => 'This is a required information'
            ),
            'alphaNumeric' => array(
                'rule' => 'alphaNumeric',
                'message' => 'Usernames must only contain letters and numbers.'
            ),
            'between' => array(
                'rule' => array('between', 5, 32),
                'message' => 'Usernames must be between 5 and 32 characters long.'
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'Username already exists please choose another name.'
            )
        ),
        'email' => array(
            'required' => array(
                'rule' => '//',
                'on' => 'create',
                'required' => true,
                'message' => 'This field is not blank!',
            ),
            'notempty' => array(
                'allowEmpty' => false,
                'rule' => 'notempty',
                'message' => 'This is a required information',
            ),
            'email' => array(
                'rule' => 'email',
                'message' => 'Please enter a valid email address. For example fred@domain.com'
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'Email already exists please choose another name.'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => '//',
                'on' => 'create',
                'required' => true,
                'message' => 'This field is not blank!',
            ),
            'notempty' => array(
                'allowEmpty' => false,
                'rule' => 'notempty',
                'message' => 'This is a required information'
            ),
            'between' => array(
                'rule' => array('between', 6, 32),
                'message' => 'Passwords must be between 6 and 32 characters long.'
            )
        ),
            're_password' => array(
              'required'=>'notEmpty',
              'match'=>array(
                'rule' => 'validatePasswdConfirm',
                'message' => 'Passwords do not match'
              )
            ),
        'fullname' => array(
            'required' => array(
                'rule' => '//',
                'on' => 'create',
                'required' => true,
                'message' => 'This field is not blank!',
            ),
            'notempty' => array(
                'allowEmpty' => false,
                'rule' => 'notempty',
                'message' => 'This is a required information'
            )
        ),
        'phone' => array(
            'required' => array(
                'rule' => '//',
                'on' => 'create',
                'required' => true,
                'message' => 'This field is not blank!',
            ),
            'notempty' => array(
                'allowEmpty' => false,
                'rule' => 'notempty',
                'message' => 'This is a required information'
            )
        ),
        'gender' => array(
            'boolean' => array(
                'allowEmpty' => true,
                'rule' => 'boolean',
                'message' => 'Incorrect value for this field'
            )
        ),
        'birthday' => array(
            'date' => array(
                'allowEmpty' => true,
                'rule' => 'date',
                'message' => 'Birthday is a required information, Please use this date format: dd-mm-yyyy. For example 17-03-2006'
            )
        ),
        'enabled' => array(
            'boolean' => array(
                'allowEmpty' => true,
                'rule' => 'boolean',
                'message' => 'Incorrect value for this field'
            )
        )
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    /**
     * Binds to block nodes through role settings
     *
     * @var array
     */
    var $hasAndBelongsToMany = array(
        'Role' => array(
            'className' => 'User.Role',
            'with' => 'User.UserRole',
            'unique' => 'keepExisting',
        )
    );

    /**
     * Called during validation operations, before validation.
     *
     * unset password if it an empty
     *
     * @return boolean
     */
    public function beforeValidate($options = array()) {
        if ($this->id && empty($this->data[$this->alias]['password'])) {
            unset($this->data[$this->alias]['password']);
        }
        return parent::beforeValidate($options);
    }

    /**
     * Before save callback
     *
     * Hash password
     *
     * @return boolean
     */
    public function beforeSave($options = array()) {
        if (!empty($this->data[$this->alias]['password'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
        }
        return parent::beforeSave($options);
    }

    /**
     * Get Core Role map value key
     * 
     * @param key to get
     * @return array
     */
    public function roleMap($key = null) {
        if (is_null($key)) {
            return $this->_roleMap;
        }
        if (isset($this->_roleMap[$key])) {
            return $this->_roleMap[$key];
        }
        return null;
    }

    /**
     * Get get role keys in active user data
     *
     * @param array $user Active user data
     * @param boolean $anonymous to include anonymous roles
     * @return array
     */
    public function getRoles($user = null, $anonymous = false) {
        $keys = array();
        if (!empty($user)) {
            $keys = (array) Set::extract('/Role/' . $this->UserRole->primaryKey, $user);
            $keys[] = $this->roleMap('authenticated');
        }
        if ($anonymous) {
            $keys[] = $this->roleMap('anonymous');
        }
        return $keys;
    }

    /**
     * Check is full access
     *
     * @param array $keys foreign keys in active user data
     * @return boolean
     */
    public function isAdministrator($keys) {
        return in_array($this->roleMap('administrator'), (array) $keys);
    }

    /**
     * Check is full access
     *
     * @param array $keys foreign keys in active user data
     * @return boolean
     */
    public function isAuthenticated($keys) {
        return in_array($this->roleMap('authenticated'), (array) $keys);
    }

    /**
     * Check anonymous access
     *
     * @param array $keys foreign keys in active user data
     * @return boolean
     */
    public function isAnonymous($keys) {
        return in_array($this->roleMap('anonymous'), (array) $keys);
    }
  function validatePasswdConfirm($data)
  {
    if ($this->data['User']['password'] !== $data['re_password'])
    {
      return false;
    }
    return true;
  }

}

?>